package com.atguigu.user.controller;

import com.atguigu.param.UserCheckParam;
import com.atguigu.param.UserLoginParam;
import com.atguigu.user.service.UserService;
import com.atguigu.utils.R;
import org.checkerframework.checker.formatter.qual.InvalidFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.atguigu.pojo.User;
import java.security.PublicKey;

/**
 * ClassName:UserController
 * Package:com.atguigu.user.controller
 * Description:
 *
 * @Author 应永豪
 * @Create 2024/4/21 13:48
 * @Version 1.0
 */

// TODO: 2024/4/21
//    定义接收参数的param，并且添加参数校验注解
//    定义Controller
//    定义service
//    定义mapper，操作哪张表就生成对应的mapper，继承Basemapper
@RestController//返回数据为json
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("check")
//    @RequestBody --将前端传过来的json转换为实体类
//    @Validated --使校验注解生效，校验注解生效需要两步
//    1.实体类属性上添加校验注解
//    2.使用时，添加 @Validated
//    将前端传过来的json转换成UserCheckParam

//    BindingResult用来获取参数校验结果，必须紧挨着被校验的类
    public R check(@RequestBody @Validated UserCheckParam userCheckParam, BindingResult result) {
//        检查是否满足检验注解的规则，如果不符合，返回true
        boolean b = result.hasErrors();
        if (b) {
            return R.fail("账号为空，不可使用");
        }

        return userService.check(userCheckParam);

    }

    @PostMapping("register")
    public R register(@RequestBody @Validated User user ,BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return R.fail("参数异常，不可注册！");
        }
        return userService.register(user);
    }

    @PostMapping("login")
    public R login(@RequestBody @Validated UserLoginParam userLoginParam,BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return R.fail("参数异常，不可登录！");
        }
        return userService.login(userLoginParam);
    }

}
